package org.finesys.samples.file.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioClient {
    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            //selector
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            //连接
            socketChannel.connect(new InetSocketAddress("localhost", 8080));


            boolean isEnding = false;

            while (!isEnding) {
                System.out.println("等待事件发生");
                //阻塞等待事件
                int readChannels = selector.select();
                if (readChannels == 0) {
                    continue;
                }
                System.out.println("事件发生了");
                //
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterable = selectionKeys.iterator();
                while (iterable.hasNext()) {
                    SelectionKey selectionKey = iterable.next();
                    //处理完成后，将事件从selectionKeys里面移除掉
                    iterable.remove();
                    if (selectionKey.isConnectable()) {
                        System.out.println("客户端连接");
                        //处理accept事件
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        if (client.isConnectionPending()) {
                            client.finishConnect();
                            System.out.println("客户端连接完成");
                            String sendMessage = "你好，服务端";
                            ByteBuffer byteBuffer = ByteBuffer.wrap(sendMessage.getBytes());
                            client.write(byteBuffer);
                            System.out.println("客户端发送初始化连接数据:" + sendMessage);
                        }
                        client.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        //处理read事件
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int count = client.read(byteBuffer);
                        if (count > 0) {
                            String receiveMessage = new String(byteBuffer.array(), 0, count);
                            System.out.println("接收到服务端消息" + receiveMessage);
                            client.register(selector, SelectionKey.OP_WRITE);
                        }
                    } else if (selectionKey.isWritable()) {
                        //处理write事件
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        //给客户端发送消息
                        String sendMessage = "你好！";
                        ByteBuffer wrap = ByteBuffer.wrap(sendMessage.getBytes());
                        client.write(wrap);
                        System.out.println("客户端向服务端发送数据：" + sendMessage);
                        client.register(selector, SelectionKey.OP_READ);
//                        isEnding=true;
                    }
                }
            }

            //关闭连接
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
